package backtrack;

import java.util.ArrayList;
import java.util.List;

/**
 * 全排列型回溯
 */
public class Solution_46 {

    /**
     * 当前操作从[0,末尾]选一个数，下一次还是
     */
    private List<List<Integer>> res = new ArrayList<>();
    private boolean[] vis;

    public List<List<Integer>> permute(int[] nums) {
        vis = new boolean[nums.length];
        backtrack(nums, new ArrayList<>());
        return res;
    }

    /**
     * 约束条件：!vis[i]
     */
    private void backtrack(int[] nums, List<Integer> path) {
        if (path.size() == nums.length) {
            res.add(new ArrayList<>(path));
            return;
        }
        for (int i = 0; i < nums.length; i++) {
            if (!vis[i]) {
                path.add(nums[i]);
                vis[i] = true;
                backtrack(nums, path);
                vis[i] = false;
                path.remove(path.size() - 1);
            }
        }
    }

    public static void main(String[] args) {
        Solution_46 solution46 = new Solution_46();
        List<List<Integer>> permute = solution46.permute(new int[]{1, 2, 3});
        permute.forEach(list -> {
            list.forEach(System.out::print);
            System.out.println();
        });
    }
}
